'''
Created on Nov 29, 2010

@author: dexen
'''

import time
import random

from dexen import BaseSlaveTask
from ranking import ranking
from ranking.ranking import ParetoRanking


def select(inds):    
    inds = sorted(inds, key=lambda rank: rank.id)
    size = len(inds)
    return inds[:size/2], inds[size/2:]

def create_new_gen(inds):
    assert len(inds) % 2 == 0
    random.shuffle(inds)
    new_gen = []
    for i in range(0, len(inds), 2):
        child1, child2 = inds[i].reproduce(inds[i+1])
        new_gen.append(child1)
        new_gen.append(child2)
    return new_gen


class FeedbackTask(BaseSlaveTask):
    def __init__(self):
        pass
    
    def __execute__(self, master_state, inds):
        print "I am in Feedback"
    
        sorted_inds = sorted(inds, key=lambda ind: ind.similarity) 
        
        dead_inds = sorted_inds[:len(inds)/2]
        alive_inds = sorted_inds[len(inds)/2:]

        for ind in dead_inds:
            ind.kill()
                
        new_gen = create_new_gen(alive_inds)
        return inds + new_gen
        

    